package com.dd.seckill.single.utils.generator;

import java.sql.*;
import java.util.HashSet;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @Author liuxianmeng
 * @CreateTime 2025/9/6 22:59
 * @Description 类功能作用说明
 */
public class DataGenerator {
    // 数据库连接配置
    private static final String URL = "jdbc:mysql://localhost:3306/dd_seckill?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "root";

    // 中文姓氏和名字库
    private static final String[] SURNAMES = {"赵", "钱", "孙", "李", "周", "吴", "郑", "王", "冯", "陈",
            "褚", "卫", "蒋", "沈", "韩", "杨", "朱", "秦", "尤", "许"};
    private static final String[] FIRST_NAMES = {
            "伟", "芳", "娜", "秀英", "敏", "静", "磊", "洋", "艳", "勇",
            "军", "杰", "娟", "强", "霞", "鹏", "宇", "超", "婷", "明",
            "平", "雪", "鑫", "亮", "建", "林", "丹", "刚", "丽", "华",
            "波", "涛", "辉", "玲", "红", "梅", "云", "飞", "阳", "兰",
            "欣", "悦", "慧", "文", "颖", "莹", "晶", "洁", "瑜", "璐",
            "瑶", "瑾", "琪", "琳", "璇", "珂", "珺", "玥", "玮", "琛",
            "瑞", "琦", "珊", "珍", "珠", "翠", "翡", "珀", "琼", "璧",
            "博", "渊", "瀚", "浩", "然", "轩", "睿", "智", "聪", "明",
            "达", "通", "晓", "悟", "慧", "颖", "敏", "捷", "迅", "疾",
            "勇", "猛", "刚", "毅", "坚", "强", "悍", "威", "武", "雄",
            "壮", "健", "康", "泰", "安", "宁", "静", "和", "平", "顺",
            "畅", "舒", "适", "宜", "佳", "美", "好", "妙", "优", "秀",
            "卓", "越", "超", "凡", "特", "殊", "异", "奇", "珍", "稀",
            "贵", "重", "宝", "贝", "金", "银", "铜", "铁", "钢", "铝",
            "石", "玉", "木", "林", "森", "树", "枝", "叶", "花", "草",
            "苗", "芽", "蕊", "蕾", "朵", "瓣", "香", "芳", "芬", "菲",
            "艳", "丽", "彩", "色", "泽", "光", "辉", "煌", "耀", "灿",
            "烂", "炫", "目", "眼", "睛", "眸", "瞳", "眉", "毛", "发",
            "肤", "肌", "肉", "骨", "血", "脉", "心", "肝", "脾", "肺",
            "肾", "胃", "肠", "胆", "脑", "头", "脸", "面", "额", "颊",
            "鼻", "口", "唇", "齿", "舌", "喉", "颈", "项", "肩", "背",
            "胸", "腹", "腰", "臀", "腿", "脚", "手", "臂", "腕", "掌",
            "指", "甲", "趾", "跟", "踪", "迹", "象", "形", "声", "音"
    };

    // 商品名称前缀和后缀
    private static final String[] PRODUCT_PREFIXES = {"高端", "豪华", "精品", "时尚", "经典", "智能", "便携", "超薄"};
    private static final String[] PRODUCT_NAMES = {"智能手机", "笔记本电脑", "平板电脑", "智能手表", "蓝牙耳机",
            "游戏主机", "数码相机", "无人机"};

    // 名字不能重复
    private static final HashSet<String> nameSet = new HashSet<>();

    public static void main(String[] args) {
        try {
            // 加载JDBC驱动
            Class.forName("com.mysql.cj.jdbc.Driver");

            // 建立数据库连接
            Connection conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
            conn.setAutoCommit(false); // 启用事务，提高插入效率

            System.out.println("开始插入用户数据...");
            insertUsers(conn, 1, 10000);

            System.out.println("开始插入商品数据...");
            //insertProducts(conn, 8);

            conn.commit();
            conn.close();

            System.out.println("数据插入完成！");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 插入用户数据
     */
    private static void insertUsers(Connection conn, int startId, int endId) throws SQLException {
        String sql = "INSERT INTO user (username, password) VALUES (?, ?)";
        PreparedStatement pstmt = conn.prepareStatement(sql);

        Random random = new Random();

        for (int i = startId; i <= endId; i++) {
            // 生成中文用户名（三个字）
            String username = null;
            boolean addSuccess = false;
            do {
                String surname = SURNAMES[random.nextInt(SURNAMES.length)];
                String name1 = FIRST_NAMES[random.nextInt(FIRST_NAMES.length)];
                String name2 = FIRST_NAMES[random.nextInt(FIRST_NAMES.length)];
                username = surname + name1 + name2;
                addSuccess = nameSet.add(username);
                // 循环 直到生成不一样的名字
                if(addSuccess) {
                    break;
                }
            } while (true);

            // 生成密码（MD5加密后的格式）
            String password = "123456"; // 123456的MD5

            pstmt.setString(1, username);
            pstmt.setString(2, password);
            pstmt.addBatch();

            // 每1000条执行一次批量插入
            if (i % 1000 == 0) {
                pstmt.executeBatch();
                System.out.println("已插入 " + i + " 条用户记录");
            }
        }

        pstmt.executeBatch(); // 执行剩余的批量插入
        pstmt.close();
    }

    /**
     * 插入商品数据
     */
    private static void insertProducts(Connection conn, int count) throws SQLException {
        String sql = "INSERT INTO seckill_goods (goods_name, original_price, seckill_price, initial_stock, available_stock, start_time, end_time) VALUES (?, ?, ?, ?, ?, ?, ?)";
        PreparedStatement pstmt = conn.prepareStatement(sql);

        ThreadLocalRandom random = ThreadLocalRandom.current();

        for (int i = 1; i <= count; i++) {
            // 生成商品名称
            String prefix = PRODUCT_PREFIXES[random.nextInt(PRODUCT_PREFIXES.length)];
            String name = PRODUCT_NAMES[random.nextInt(PRODUCT_NAMES.length)];
            String goodsName = prefix + name;

            // 生成价格（原价在1000-10000之间，秒杀价是原价的60-90%）
            double originalPrice = random.nextDouble(1000, 10000);
            double discount = random.nextDouble(0.6, 0.9);
            double seckillPrice = originalPrice * discount;

            // 生成库存（50-200之间）
            int stock = random.nextInt(50, 201);

            // 设置秒杀时间（当前时间后的1-30天内）
            long now = System.currentTimeMillis();
            long startTime = now + random.nextLong(86400000, 2592000000L); // 1-30天
            long endTime = startTime + random.nextLong(3600000, 86400000); // 1-24小时后结束

            pstmt.setString(1, goodsName);
            pstmt.setDouble(2, originalPrice);
            pstmt.setDouble(3, seckillPrice);
            pstmt.setInt(4, stock);
            pstmt.setInt(5, stock);
            pstmt.setTimestamp(6, new Timestamp(startTime));
            pstmt.setTimestamp(7, new Timestamp(endTime));

            pstmt.addBatch();
        }

        pstmt.executeBatch();
        pstmt.close();
    }
}